package com.zenithmind.user.service.impl;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.user.mapper.UserMapper;
import com.zenithmind.user.pojo.domain.Role;
import com.zenithmind.user.pojo.domain.User;
import com.zenithmind.user.pojo.domain.UserRole;
import com.zenithmind.user.pojo.dto.LoginDTO;
import com.zenithmind.user.pojo.dto.SimpleLoginDTO;
import com.zenithmind.user.pojo.dto.UserProfileUpdateDTO;
import com.zenithmind.user.pojo.query.UserQuery;
import com.zenithmind.user.pojo.vo.UserVO;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.common.result.ResultCode;
import com.zenithmind.user.security.OAuth2TokenUtils;
import com.zenithmind.user.service.PermissionService;
import com.zenithmind.user.service.RoleService;
import com.zenithmind.user.service.UserRoleService;
import com.zenithmind.user.service.UserService;
import com.zenithmind.user.utils.PasswordUtils;
import com.zenithmind.common.utils.RedisUtils;
import com.zenithmind.common.config.BloomFilterConfig;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zenithmind.common.constant.CacheConstants;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.common.exception.ForbiddenException;
import com.zenithmind.common.exception.NotFoundException;
import com.zenithmind.common.exception.UnauthorizedException;
import com.zenithmind.common.exception.ValidationException;
import com.zenithmind.user.pojo.dto.AdminLoginDTO;
import com.zenithmind.user.service.VerificationCodeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.zenithmind.user.pojo.dto.RegisterDTO;
import com.zenithmind.common.annotation.DataCache;
import com.zenithmind.common.annotation.DataCacheEvict;
import com.zenithmind.common.security.SecurityUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    
    // 用户缓存相关常量
    private static final String USER_ID_KEY_PREFIX = "user:id:";
    private static final String USER_USERNAME_KEY_PREFIX = "user:username:";
    private static final String USER_EMAIL_KEY_PREFIX = "user:email:";
    private static final String USER_LOCK_KEY_PREFIX = "lock:user:";
    private static final long USER_CACHE_EXPIRE = 3600L; // 1小时

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private VerificationCodeService verificationCodeService;
    
    @Autowired
    private RedisUtils redisUtils;

    @Value("${verification.code.admin-only:true}")
    private boolean adminVerificationOnly;


    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private OAuth2TokenUtils oauth2TokenUtils;

    @Value("${verification.code.expire-minutes:5}")
    private int expireMinutes; // Get expire time from config

    // 新的领域服务
    @Autowired
    private com.zenithmind.user.service.domain.UserDomainService userDomainService;

    @Autowired
    private com.zenithmind.user.service.domain.AuthenticationService authenticationService;


    /**
     * 用户登录方法
     * 判断用户名和密码是否为空，然后查询用户信息并验证密码
     *
     * @param loginDTO 登录参数对象，包含用户名和密码
     * @return 登录结果，包含用户信息
     */
    @Override
    @Transactional
    public Result<UserVO> login(LoginDTO loginDTO) {
        // 委托给认证服务处理
        return authenticationService.login(loginDTO);
    }

    /**
     * 简单用户登录方法（测试用，不需要验证码）
     * 判断用户名和密码是否为空，然后查询用户信息并验证密码
     *
     * @param simpleLoginDTO 简单登录参数对象，包含用户名和密码
     * @return 登录结果，包含用户信息
     */
    @Override
    @Transactional
    public Result<UserVO> simpleLogin(SimpleLoginDTO simpleLoginDTO) {
        // 判断账号和密码是否为空
        if (StringUtils.isBlank(simpleLoginDTO.getUsername()) ||
                StringUtils.isBlank(simpleLoginDTO.getPassword())) {
            return Result.fail(ResultCode.INVALID_CREDENTIALS);
        }

        // 根据用户名查询用户
        User user = getUserByUsername(simpleLoginDTO.getUsername());
        if (user == null) {
            return Result.fail(ResultCode.INVALID_CREDENTIALS);
        }

        // 验证密码
        if (PasswordUtils.compare(simpleLoginDTO.getPassword(), user.getPassword())) {
            // 登录成功
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);

            // 获取并设置角色信息
            String rolesString = "USER"; // 默认角色
            LambdaQueryWrapper<UserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
            userRoleQueryWrapper.eq(UserRole::getUserId, user.getId());
            UserRole userRole = userRoleService.getOne(userRoleQueryWrapper);
            if (userRole != null) {
                Role role = roleService.getById(userRole.getRoleId());
                if (role != null) {
                    userVO.setRole(role);
                    rolesString = role.getRoleCode();
                }
            }

            HashMap<String, Object> claims = new HashMap<>();
            claims.put("user_id", user.getId());
            claims.put("sub", user.getUsername());
            claims.put("preferred_username", user.getUsername());
            
            // 将角色作为列表传递，确保可以被正确解析
            List<String> rolesList = new ArrayList<>();
            rolesList.add(rolesString);
            claims.put("roles", rolesList);
            
            userVO.setToken(oauth2TokenUtils.createJwt(claims));
            return Result.success(userVO);
        } else {
            // 密码错误
            return Result.fail(ResultCode.INVALID_CREDENTIALS);
        }
    }

    /**
     * 根据用户名获取用户信息
     * 使用缓存注解自动处理缓存
     */
    @DataCache(prefix = "user:username", key = "#username", expireTime = 3600)
    public User getUserByUsername(String username) {
        if (StringUtils.isBlank(username)) {
            return null;
        }
        return getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }

    /**
     * 用户注册方法
     * 判断用户名、邮箱和密码是否为空，检查用户名和邮箱是否已存在，然后加密密码并保存用户信息。
     * 验证码已在Controller层校验。
     *
     * @param registerDTO 注册参数对象，包含用户名、邮箱、密码等
     * @return 注册结果，包含用户信息
     */
    @Override
    @Transactional
    public Result<UserVO> register(RegisterDTO registerDTO) {
        if (StringUtils.isBlank(registerDTO.getUsername()) || 
            StringUtils.isBlank(registerDTO.getEmail()) || 
            StringUtils.isBlank(registerDTO.getPassword())) {
            log.warn("注册信息不完整: {}", registerDTO);
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "用户名、邮箱和密码不能为空", null);
        }

        // 检查用户名是否已存在 - 使用布隆过滤器和缓存防止缓存穿透
        String usernameKey = USER_USERNAME_KEY_PREFIX + registerDTO.getUsername();
        User existUserByUsername = redisUtils.getWithPenetrationPrevention(usernameKey,
            () -> getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, registerDTO.getUsername())),
            USER_CACHE_EXPIRE);
            
        if (existUserByUsername != null) {
            log.warn("用户名已存在: {}", registerDTO.getUsername());
            return Result.fail(ResultCode.USERNAME_EXIST);
        }

        // 检查邮箱是否已存在 - 使用布隆过滤器和缓存防止缓存穿透
        String emailKey = USER_EMAIL_KEY_PREFIX + registerDTO.getEmail();
        User existUserByEmail = redisUtils.getWithPenetrationPrevention(emailKey,
            () -> getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, registerDTO.getEmail())),
            USER_CACHE_EXPIRE);
            
        if (existUserByEmail != null) {
            log.warn("邮箱已注册: {}", registerDTO.getEmail());
            return Result.fail(ResultCode.EMAIL_EXIST);
        }

        User newUser = new User();
        newUser.setUsername(registerDTO.getUsername());
        newUser.setEmail(registerDTO.getEmail());
        newUser.setPassword(PasswordUtils.encryption(registerDTO.getPassword()));

        boolean saved = save(newUser);
        if (!saved) {
            log.error("保存新用户失败: {}", newUser);
            return Result.fail(ResultCode.SYSTEM_ERROR);
        }

        // 注册成功后，将用户信息添加到布隆过滤器
        redisUtils.addToBloomFilter(BloomFilterConfig.USER_ID_FILTER, newUser.getId());
        redisUtils.addToBloomFilter(BloomFilterConfig.USER_EMAIL_FILTER, newUser.getEmail());
        
        // 删除可能存在的缓存
        redisUtils.delete(USER_USERNAME_KEY_PREFIX + newUser.getUsername());
        redisUtils.delete(USER_EMAIL_KEY_PREFIX + newUser.getEmail());

            UserVO userVO = new UserVO();
        BeanUtils.copyProperties(newUser, userVO);
        log.info("用户注册成功: {}", userVO.getUsername());
            return Result.success(userVO);
    }

    /**
     * 获取当前登录用户信息
     * 通过JWT工具获取用户ID，然后查询并返回用户信息
     *
     * @return 当前用户信息
     */
    @Override
    public UserVO getCurrentUser() {
        String userId = SecurityUtils.getCurrentUserId();
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        return getUserById(userId);
    }

    /**
     * 根据ID获取用户信息
     * 使用@DataCache注解自动处理缓存
     *
     * @param id 用户ID
     * @return 用户信息VO对象
     */
    @Override
    @DataCache(prefix = "user", key = "#id", expireTime = 3600)
    public UserVO getUserById(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }

        User user = getById(id);
        if (user == null) {
            return null;
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        // 设置兼容性字段
        userVO.setPhone(user.getMobile()); // 兼容disk-service和article-service
        userVO.setIntroduction(user.getIntro()); // 兼容article-service

        // 获取并设置角色信息
        LambdaQueryWrapper<UserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
        userRoleQueryWrapper.eq(UserRole::getUserId, id);
        UserRole userRole = userRoleService.getOne(userRoleQueryWrapper);
        if (userRole != null) {
            Role role = roleService.getById(userRole.getRoleId());
            if (role != null) {
                userVO.setRole(role);
            }
        }

        return userVO;
    }

    /**
     * 更新当前登录用户信息
     * 使用@DataCacheEvict注解自动清除缓存
     *
     * @param updateDTO 用户更新参数对象
     * @return 更新后的用户信息
     */
    @Override
    @Transactional
    @DataCacheEvict(prefix = "user", key = "#userId")
    public UserVO updateLoginUser(UserProfileUpdateDTO updateDTO) {
        String userId = SecurityUtils.getCurrentUserId();
        if (StringUtils.isBlank(userId)) {
            throw new UnauthorizedException("未登录");
        }

        // 1. 查询用户是否存在
        User user = getById(userId);
        if (user == null) {
            throw new NotFoundException("用户不存在");
        }

        // 2. 更新用户信息
        if (StringUtils.isNotBlank(updateDTO.getNickname())) {
            user.setNickname(updateDTO.getNickname());
        }
        if (StringUtils.isNotBlank(updateDTO.getEmail())) {
            user.setEmail(updateDTO.getEmail());
        }
        if (StringUtils.isNotBlank(updateDTO.getMobile())) {
            user.setMobile(updateDTO.getMobile());
        }
        if (StringUtils.isNotBlank(updateDTO.getAvatar())) {
            user.setAvatar(updateDTO.getAvatar());
        }
        if (StringUtils.isNotBlank(updateDTO.getIntro())) {
            user.setIntro(updateDTO.getIntro());
        }

        updateById(user);
        
        // 更新后重新获取用户信息
        return getUserById(userId);
    }

    /**
     * 用户列表分页查询
     * 根据用户查询参数进行分页查询，并返回查询结果
     *
     * @param userQuery 用户查询参数对象，包含分页信息和查询条件
     * @return 用户列表分页查询结果
     */
    @Override
    public PageResult<UserVO> userPage(UserQuery userQuery) {
        Page<User> page = userQuery.toPage();
        Page<User> userPage = lambdaQuery()
                .eq(StrUtil.isNotBlank(userQuery.getUsername()), User::getUsername, userQuery.getUsername())
                .eq(StrUtil.isNotBlank(userQuery.getNickname()), User::getNickname, userQuery.getNickname())
                .eq(StrUtil.isNotBlank(userQuery.getEmail()), User::getEmail, userQuery.getEmail())
                .eq(StrUtil.isNotBlank(userQuery.getMobile()), User::getMobile, userQuery.getMobile())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .page(page);
        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).toList();
        return new PageResult<>(userVOList, userPage.getTotal(), userPage.getCurrent(), userPage.getSize());
    }

    /**
     * 更新用户状态
     */
    @Override
    @Transactional
    public UserVO updateStatus(User user) {
        if (user == null || StringUtils.isBlank(user.getId())) {
            throw new ValidationException("用户ID不能为空");
        }
        
        // 使用分布式锁进行更新，确保原子性
        String userKey = USER_ID_KEY_PREFIX + user.getId();
        String lockKey = USER_LOCK_KEY_PREFIX + user.getId();
        
        redisUtils.update(userKey, lockKey, () -> {
            User existUser = getById(user.getId());
            if (existUser == null) {
                throw new NotFoundException("用户不存在");
            }
            existUser.setStatus(user.getStatus());
            updateById(existUser);
        });
        
        // 更新后重新获取用户信息
        return getUserById(user.getId());
    }

    /**
     * 更新用户角色
     */
    @Override
    @Transactional
    public UserVO updateRole(UserRole userRole) {
        if (userRole == null || StringUtils.isBlank(userRole.getUserId()) || StringUtils.isBlank(userRole.getRoleId())) {
            throw new ValidationException("用户ID和角色ID不能为空");
        }
        
        // 使用分布式锁进行更新，确保原子性
        String userKey = USER_ID_KEY_PREFIX + userRole.getUserId();
        String lockKey = USER_LOCK_KEY_PREFIX + userRole.getUserId();
        
        redisUtils.update(userKey, lockKey, () -> {
            // 1. 查询用户是否存在
            User user = getById(userRole.getUserId());
            if (user == null) {
                throw new NotFoundException("用户不存在");
            }
            
            // 2. 查询角色是否存在
            Role role = roleService.getById(userRole.getRoleId());
            if (role == null) {
                throw new NotFoundException("角色不存在");
            }
            
            // 3. 更新用户角色
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRole::getUserId, userRole.getUserId());
            userRoleService.remove(queryWrapper);
            userRoleService.save(userRole);
        });
        
        // 更新后重新获取用户信息
        return getUserById(userRole.getUserId());
    }

    /**
     * 更新用户已用存储空间
     */
    @Override
    @Transactional
    public boolean updateStorageUsed(String userId, long fileSize) {
        if (StringUtils.isBlank(userId)) {
            throw new ValidationException("用户ID不能为空");
        }
        
        // 使用分布式锁进行更新，确保原子性
        String userKey = USER_ID_KEY_PREFIX + userId;
        String lockKey = USER_LOCK_KEY_PREFIX + userId;
        
        try {
            redisUtils.update(userKey, lockKey, () -> {
                User user = getById(userId);
        if (user == null) {
                    throw new NotFoundException("用户不存在");
        }

                long currentUsed = user.getStorageUsed() != null ? user.getStorageUsed() : 0;
                long newUsed = currentUsed + fileSize;
                if (newUsed < 0) {
                    newUsed = 0; // 防止负数
                }
                
                long storageLimit = user.getStorageLimit() != null ? user.getStorageLimit() : 0;
                if (storageLimit > 0 && newUsed > storageLimit) {
                    throw new BusinessException("存储空间不足");
                }
                
                user.setStorageUsed(newUsed);
                updateById(user);
            });
            
            return true;
        } catch (Exception e) {
            log.error("更新用户存储空间失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 重置用户密码
     */
    @Override
    @Transactional
    public void resetPassword(User user) {
        if (user == null || StringUtils.isBlank(user.getId()) || StringUtils.isBlank(user.getPassword())) {
            throw new ValidationException("用户ID和密码不能为空");
        }
        
        // 使用分布式锁进行更新，确保原子性
        String userKey = USER_ID_KEY_PREFIX + user.getId();
        String lockKey = USER_LOCK_KEY_PREFIX + user.getId();
        
        redisUtils.update(userKey, lockKey, () -> {
            User existUser = getById(user.getId());
            if (existUser == null) {
                throw new NotFoundException("用户不存在");
        }

            existUser.setPassword(PasswordUtils.encryption(user.getPassword()));
            updateById(existUser);
        });
    }
    
    /**
     * 批量删除用户
     */
    @Override
    @Transactional
    public void deleteBatch(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        
        // 批量删除用户
        removeByIds(ids);
        
        // 删除用户角色关系
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserRole::getUserId, ids);
        userRoleService.remove(queryWrapper);
        
        // 删除缓存
        for (String id : ids) {
            String userKey = USER_ID_KEY_PREFIX + id;
            redisUtils.delete(userKey);
            
            // 从布隆过滤器中删除用户ID
            // 注意：布隆过滤器不支持删除操作，这里只是删除缓存
        }
    }
    
    /**
     * 添加或更新用户
     */
    @Override
    @Transactional
    public UserVO addOrUpdateUser(User user) {
        if (user == null) {
            throw new ValidationException("用户信息不能为空");
        }

        // 检查用户名是否已存在
        if (StringUtils.isNotBlank(user.getUsername())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername());
            if (StringUtils.isNotBlank(user.getId())) {
                queryWrapper.ne(User::getId, user.getId()); // 排除自身
            }
            long count = count(queryWrapper);
            if (count > 0) {
                throw new BusinessException("用户名已存在");
            }
        }
        
        // 检查邮箱是否已存在
        if (StringUtils.isNotBlank(user.getEmail())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail, user.getEmail());
            if (StringUtils.isNotBlank(user.getId())) {
                queryWrapper.ne(User::getId, user.getId()); // 排除自身
            }
            long count = count(queryWrapper);
            if (count > 0) {
                throw new BusinessException("邮箱已存在");
            }
        }

        // 加密密码
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(PasswordUtils.encryption(user.getPassword()));
        } else if (StringUtils.isBlank(user.getId())) {
            // 新增用户必须设置密码
            throw new ValidationException("密码不能为空");
    }

        boolean result;
        if (StringUtils.isBlank(user.getId())) {
            // 新增用户
            result = save(user);
            
            // 添加到布隆过滤器
            if (result) {
                redisUtils.addToBloomFilter(BloomFilterConfig.USER_ID_FILTER, user.getId());
                if (StringUtils.isNotBlank(user.getEmail())) {
                    redisUtils.addToBloomFilter(BloomFilterConfig.USER_EMAIL_FILTER, user.getEmail());
                }
            }
        } else {
            // 更新用户
            String userKey = USER_ID_KEY_PREFIX + user.getId();
            String lockKey = USER_LOCK_KEY_PREFIX + user.getId();
            
            redisUtils.update(userKey, lockKey, () -> {
                // 查询用户是否存在
                User existUser = getById(user.getId());
                if (existUser == null) {
                    throw new NotFoundException("用户不存在");
                }
                
                // 密码为空时，保留原密码
                if (StringUtils.isBlank(user.getPassword())) {
                    user.setPassword(existUser.getPassword());
            }
                
            updateById(user);
            });
            result = true;
        }
        
        if (!result) {
            throw new BusinessException("保存用户失败");
        }
        
        return getUserById(user.getId());
    }

    /**
     * 管理员登录
     */
    @Override
    @Transactional
    public Result<UserVO> adminLogin(AdminLoginDTO adminLoginDTO) {
        // 验证参数
        if (StringUtils.isBlank(adminLoginDTO.getUsername()) || StringUtils.isBlank(adminLoginDTO.getPassword())) {
            return Result.fail(ResultCode.INVALID_CREDENTIALS);
        }

        // 根据用户名查询用户 - 直接从数据库查询，避免缓存类型转换问题
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, adminLoginDTO.getUsername()));
        if (user == null) {
            return Result.fail(ResultCode.INVALID_CREDENTIALS);
        }

        // 验证密码
        if (!PasswordUtils.compare(adminLoginDTO.getPassword(), user.getPassword())) {
            return Result.fail(ResultCode.INVALID_CREDENTIALS);
        }

        // 验证是否是管理员（完善：支持多角色，必须有ADMIN角色）
        List<UserRole> userRoles = userRoleService.list(
            new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId())
        );
        Role adminRole = null;
        UserRole adminUserRole = null;
        if (userRoles != null && !userRoles.isEmpty()) {
            for (UserRole ur : userRoles) {
                Role role = roleService.getById(ur.getRoleId());
                if (role != null && "ADMIN".equalsIgnoreCase(role.getRoleCode())) {
                    adminRole = role;
                    adminUserRole = ur;
                    break;
                }
            }
        }
        if (adminRole == null) {
            // 没有管理员角色，禁止登录
            return Result.fail(ResultCode.FORBIDDEN, "非管理员用户禁止登录");
        }
        UserRole userRole = adminUserRole; // 兼容后续逻辑

        // 创建UserVO对象
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        // 获取并设置角色信息
        Role role = roleService.getById(userRole.getRoleId());
        if (role != null) {
            userVO.setRole(role);
        }

        // 创建Token，确保角色信息正确
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("user_id", user.getId());
        claims.put("sub", user.getUsername());
        claims.put("preferred_username", user.getUsername());
        
        // 将角色作为列表传递，确保可以被正确解析
        List<String> rolesList = new ArrayList<>();
        rolesList.add(role != null ? role.getRoleCode() : "ADMIN");
        claims.put("roles", rolesList);
        
        userVO.setToken(oauth2TokenUtils.createJwt(claims));

        return Result.success(userVO);
    }

    /**
     * 从JWT中获取用户ID
     */
    public String getUserIdFromJwtUtils() {
        return SecurityUtils.getCurrentUserId();
    }
}
